
package com.cse210.grocerwe.server;

import org.restlet.resource.ServerResource;
import com.cse210.grocerwe.common.*;
import com.cse210.grocerwe.client.*;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import com.google.appengine.api.datastore.KeyFactory;

public class APIResourceB extends ServerResource implements
APIInterfaceB
{
	PersistenceManager pm;
	
	@Post
	public SGroup[] getGroups(){
		pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(MapUserToGroup.class);
		q.setFilter("user == x");
		q.declareParameters("String x");
		
		@SuppressWarnings("unchecked")
		List<MapUserToGroup> groupmaps = (List<MapUserToGroup>) q.execute((String) getRequest().getAttributes().get("user"));
		
		SGroup[] groups = new SGroup[groupmaps.size()];
		for(int i = 0; i <groupmaps.size(); i++)
		{
			String groupkey = groupmaps.get(i).getGroup();
			ShoppingGroup sg = pm.getObjectById(ShoppingGroup.class,KeyFactory.stringToKey(groupkey));
			groups[i] = sg.toSGroup();
		}
		pm.close();
		return groups;
	}
	
	@Put
    public void editItem(SItem item)
	{
		pm = PMF.get().getPersistenceManager();
    	ShoppingItem si = new ShoppingItem(item);
        try {
            pm.makePersistent(si);
        } finally {
            pm.close();
        }
	}

}
